import { LitElement, html, css } from 'lit';
import { customElement, property, state } from 'lit/decorators.js';

/**
 * Dialog对话框组件
 * @element zss-dialog
 * @slot default - 对话框内容
 * @slot title - 对话框标题
 * @slot footer - 对话框底部
 */
@customElement('zss-dialog')
export class ZssDialog extends LitElement {
  static styles = css`
    :host {
      display: none;
    }

    :host([visible]) {
      display: block;
    }

    .dialog-overlay {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: rgba(0, 0, 0, 0.5);
      z-index: 2000;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .dialog {
      background: var(--zss-bg-color);
      border-radius: var(--zss-border-radius-base);
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      min-width: 400px;
      max-width: 90vw;
      max-height: 90vh;
      display: flex;
      flex-direction: column;
    }

    .dialog__header {
      padding: 20px 20px 10px;
      border-bottom: 1px solid var(--zss-border-color-lighter);
    }

    .dialog__title {
      font-size: var(--zss-font-size-large);
      font-weight: var(--zss-font-weight-primary);
      color: var(--zss-text-color-primary);
      margin: 0;
    }

    .dialog__close {
      position: absolute;
      top: 20px;
      right: 20px;
      background: none;
      border: none;
      font-size: 16px;
      cursor: pointer;
      color: var(--zss-text-color-secondary);
      padding: 0;
      width: 24px;
      height: 24px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: var(--zss-border-radius-base);
    }

    .dialog__close:hover {
      background-color: var(--zss-fill-color-light);
      color: var(--zss-text-color-regular);
    }

    .dialog__body {
      padding: 30px 20px;
      flex: 1;
      overflow: auto;
      color: var(--zss-text-color-regular);
    }

    .dialog__footer {
      padding: 10px 20px 20px;
      border-top: 1px solid var(--zss-border-color-lighter);
      display: flex;
      justify-content: flex-end;
      gap: 10px;
    }

    .dialog--fullscreen {
      width: 100vw;
      height: 100vh;
      max-width: none;
      max-height: none;
      border-radius: 0;
    }

    .dialog--center .dialog__footer {
      justify-content: center;
    }

    .fade-enter-active,
    .fade-leave-active {
      transition: opacity 0.3s;
    }

    .fade-enter-from,
    .fade-leave-to {
      opacity: 0;
    }

    .zoom-enter-active,
    .zoom-leave-active {
      transition: all 0.3s;
    }

    .zoom-enter-from,
    .zoom-leave-to {
      opacity: 0;
      transform: scale(0.9);
    }
  `;

  /**
   * 是否显示对话框
   * @attr visible
   */
  @property({ type: Boolean })
  visible = false;

  /**
   * 对话框标题
   * @attr title
   */
  @property({ type: String })
  title = '';

  /**
   * 是否显示关闭按钮
   * @attr show-close
   */
  @property({ type: Boolean })
  showClose = true;

  /**
   * 点击遮罩层是否关闭对话框
   * @attr close-on-click-modal
   */
  @property({ type: Boolean })
  closeOnClickModal = true;

  /**
   * 是否全屏显示
   * @attr fullscreen
   */
  @property({ type: Boolean })
  fullscreen = false;

  /**
   * 是否居中显示
   * @attr center
   */
  @property({ type: Boolean })
  center = false;

  /**
   * 自定义类名
   * @attr custom-class
   */
  @property({ type: String })
  customClass = '';

  /**
   * 宽度
   * @attr width
   */
  @property({ type: String })
  width = '50%';

  @state()
  private isVisible = false;

  private handleOverlayClick(e: Event) {
    if (this.closeOnClickModal && e.target === e.currentTarget) {
      this.close();
    }
  }

  private handleCloseClick() {
    this.close();
  }

  private close() {
    this.visible = false;
    this.dispatchEvent(new CustomEvent('close'));
  }

  private handleKeydown = (e: KeyboardEvent) => {
    if (e.key === 'Escape' && this.visible) {
      this.close();
    }
  };

  connectedCallback() {
    super.connectedCallback();
    document.addEventListener('keydown', this.handleKeydown);
  }

  disconnectedCallback() {
    document.removeEventListener('keydown', this.handleKeydown);
    super.disconnectedCallback();
  }

  updated(changedProperties: Map<string, any>) {
    if (changedProperties.has('visible')) {
      if (this.visible) {
        this.isVisible = true;
        // 阻止背景滚动
        document.body.style.overflow = 'hidden';
      } else {
        // 恢复背景滚动
        document.body.style.overflow = '';
        
        // 添加淡出动画
        setTimeout(() => {
          this.isVisible = false;
        }, 300);
      }
    }
  }

  render() {
    if (!this.isVisible) {
      return html``;
    }

    const dialogClasses = [
      'dialog',
      this.fullscreen ? 'dialog--fullscreen' : '',
      this.center ? 'dialog--center' : '',
      this.customClass
    ].filter(Boolean).join(' ');

    const dialogStyle = {
      width: this.fullscreen ? '100%' : this.width
    };

    return html`
      <div 
        class="dialog-overlay"
        @click=${this.handleOverlayClick}
      >
        <div 
          class=${dialogClasses}
          style=${`width: ${dialogStyle.width}`}
        >
          <!-- 头部 -->
          ${this.title || this.showClose ? html`
            <div class="dialog__header">
              ${this.title ? html`
                <h2 class="dialog__title">
                  <slot name="title">${this.title}</slot>
                </h2>
              ` : ''}
              
              ${this.showClose ? html`
                <button 
                  class="dialog__close"
                  @click=${this.handleCloseClick}
                >
                  ×
                </button>
              ` : ''}
            </div>
          ` : ''}

          <!-- 内容 -->
          <div class="dialog__body">
            <slot></slot>
          </div>

          <!-- 底部 -->
          <div class="dialog__footer">
            <slot name="footer"></slot>
          </div>
        </div>
      </div>
    `;
  }

  /**
   * 打开对话框
   */
  open() {
    this.visible = true;
  }

  /**
   * 关闭对话框
   */
  closeDialog() {
    this.close();
  }
}

declare global {
  interface HTMLElementTagNameMap {
    'zss-dialog': ZssDialog;
  }
}